package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import com.heima.user.service.ApUserService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @author stone
 * @description 针对表【ap_user_realname(APP实名认证信息表)】的数据库操作Service实现
 * @createDate 2023-02-26 16:54:24
 */
@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname>
        implements ApUserRealnameService {


    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {

        dto.checkParam();

        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.<ApUserRealname>lambdaQuery().eq(!Objects.isNull(dto.getStatus()), ApUserRealname::getStatus, dto.getStatus());
        IPage<ApUserRealname> realNameIPage = this.page(page, wrapper);
        return new PageResponseResult(dto.getPage(), dto.getSize(), realNameIPage.getTotal(), realNameIPage.getRecords());
    }

    @Autowired
    private ApUserService apUserService;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        if (Objects.isNull(dto)) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        if (Objects.isNull(dto.getId())) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE, "实名认证ID不能为空");
        }
        // 查询当前认证用户是否在 APP端有当前用户
        ApUserRealname userRealName = this.getOne(Wrappers.<ApUserRealname>lambdaQuery().eq(ApUserRealname::getUserId, dto.getId()));

        if (Objects.isNull(userRealName)) {
            log.error("实名认证信息不存在，userRealnameId：{}", dto.getId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前认证用户信息不存在");
        }
        if (!AdminConstants.WAIT_AUTH.equals(userRealName.getStatus())) {
            log.error("实名认证信息不是待审核状态，userRealnameId：{}", dto.getId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "实名认证信息不是待审核状态");
        }

        // 查询关联的用户信息是否存在
        ApUser apUser = apUserService.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getId, dto.getId()));
        if (Objects.isNull(apUser)) {
            log.error("查询关联的用户信息不存在，userRealnameId：{}", dto.getId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "查询关联的用户信息不存在");
        }

        // 修改状态
        userRealName.setStatus(status);
        userRealName.setUpdatedTime(new Date());
        if (StringUtils.isNotBlank(dto.getMsg())) {
            userRealName.setReason(dto.getMsg());
        }
        this.updateById(userRealName);

        // 认证状态如果为 通过
        if (AdminConstants.PASS_AUTH.equals(status)) {
            //  创建自媒体账户
            WmUser wmUser = createWmUser(dto, apUser);
            // 创建作者信息
            createApAuthor(wmUser);
        }

        return null;
    }

    @Autowired
    private ArticleFeign articleFeign;

    private void createApAuthor(WmUser wmUser) {
        ResponseResult<ApAuthor> result = articleFeign.findByUserId(wmUser.getId());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, result.getErrorMessage());
        }

        ApAuthor apAuthor = result.getData();


        if (!Objects.isNull(apAuthor)) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "作者已存在");
        }

        apAuthor = new ApAuthor();
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(2);
        apAuthor.setUserId(wmUser.getApUserId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());
        ResponseResult responseResult = articleFeign.save(apAuthor);
        if (!responseResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, responseResult.getErrorMessage());
        }


    }

    @Autowired
    private WemediaFeign wemediaFeign;

    private WmUser createWmUser(AuthDTO dto, ApUser apUser) {

        // 查询自媒体用户是否存在
        ResponseResult<WmUser> wmUserResponseResult = wemediaFeign.findByName(apUser.getName());
        if (!wmUserResponseResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, wmUserResponseResult.getErrorMessage());
        }
        WmUser wmUser = wmUserResponseResult.getData();
        if (!Objects.isNull(wmUser)) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "自媒体账户已存在");
        }

        wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setNickname("");
        wmUser.setImage("");
        wmUser.setLocation("");
        wmUser.setPhone("");
        wmUser.setStatus(9);
        wmUser.setEmail("");
        wmUser.setType(0);
        wmUser.setScore(0);
        wmUser.setLoginTime(new Date());
        wmUser.setCreatedTime(new Date());

        ResponseResult<WmUser> wmUserResponseResult1 = wemediaFeign.save(wmUser);
        if (!wmUserResponseResult1.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, wmUserResponseResult1.getErrorMessage());
        }

        return wmUserResponseResult1.getData();
    }
}




